import pandas as pd

import util.lib as lib
import util.util as utils
import util.mydecorator

from daily import get_daily_share_file_name as get_daily_share_file_name
from daily import daily_share_file_exists as daily_share_file_exists
from daily import get_daily_df


def get_data(stock, monitor):
    print(stock)

    start = monitor['start']
    end = monitor['end']
    type = monitor['type']
    count = monitor['count']

    if daily_share_file_exists(stock) == False:
        return None

    data = get_daily_df(stock)

    # 过滤在统计日期之后上市的个股
    if data.iloc[0].name.strftime("%Y-%m-%d") > start:
        return None

    if end is not None:
        df = data[start:end].copy()
    else:
        df = data[start:].copy()

    if type == "high":
        base_price = df.iloc[0].high
    elif type == "close":
        if data[:start].iloc[-1].name.strftime("%Y-%m-%d") == start:
            base_price = data[:start].iloc[-2].close
        else:
            base_price = data[:start].iloc[-1].close

    
    df["year_pct"] = (df.close - base_price) / base_price * 100
    df["year_pct"] = df["year_pct"].round(2)

    return { 
        "base_price": base_price, 
        "df": utils.merge(df[0:1], df[-1 * count:], False) 
    }

def task(stocks, writer, monitor):
    stocks = stocks.set_index('name',drop=False)
    stocks["base_price"] = 0.0
    year_dict = {}
    for stock in stocks['name']:
        ret = get_data(stock, monitor)
        if ret is None:
            continue
        year_dict[stock] = ret['df'].year_pct
        stocks.loc[stock, "base_price"] = ret['base_price']
    year_ret = pd.DataFrame(year_dict)


    # 按时间倒序
    year_ret = year_ret.sort_index(ascending=False)
    tmp = year_ret.T
    sortKey = tmp.columns.tolist()[0]
    print("排序：", sortKey)
    tmp = tmp.sort_values(by=sortKey, ascending=False)

    tmp = pd.merge(stocks[['base_price','wg_industry','category']], tmp,left_index=True, right_index=True, how='right')
    tmp['monitor_date'] = monitor['start']
    tmp.to_excel(writer, sheet_name= monitor['start'])


# 要监控的具体日期
def get_monitors():
    return [
        {
            'start' : "2024-10-08",
            'end' : None,
            'type': 'high',
            'count': 80,
        },
        {
            'start' : "2025-01-01",
            'end' : "2025-12-31",
            'type': 'close',
            'count': 260,
        },
        {
            'start' : "2025-04-07",
            'end' : None,
            'type': 'close',
            'count': 80,
        },
        {
            'start' : "2025-10-13",
            'end' : None,
            'type': 'close',
            'count': 50,
            'introduce': "贸易战",
        },
    ]


writer = None

@util.mydecorator.calTime
def job():
    writer = pd.ExcelWriter(lib.data_path + "daily_monitor.xlsx")

    stocks = lib.lib_get_all_stock()[['name','category',"rank","wg_industry"]]
    for monitor in get_monitors():
        task(stocks, writer, monitor)

    writer.close()

# 对某个交易日的价格监控
if __name__ == "__main__":
    job()